<template>
  <div class="order-page">
    <!-- 收货地址 -->
    <div class="address-wrapper">
      <p class="header">收货地址</p>
      <el-button class="btn-add" type="text" icon="el-icon-plus" @click="addAddress">新增收货地址</el-button>
      <div class="address-content" v-if="addressrList.length">
        <div class="content">
          <div class="content-left">
            <div class="address-first">
              <p class="address-default">
                <span>{{defaultAds.name}}</span>
                <span>{{defaultAds.provinceName}}</span>
              </p>
            </div>
            <span class="name">{{defaultAds.name}}</span>
            <span>{{defaultAds.areaName}} {{defaultAds.address}} </span>
            <span class="phone">{{defaultAds.mobile}}</span>
          </div>
          <div class="content-right">
            <span class="default" v-if="defaultAds.status === 1">默认地址</span>
            <span class="set" @click="setDefault(defaultAds.id)" v-if="defaultAds.status === 0">设为默认地址</span>
            <span class="edit" @click="editAddress(defaultAds.id)">编辑</span>
            <span class="edit" @click="delAddress(defaultAds.id, defaultAds.status)">删除</span>
          </div>
        </div>
        <div class="more-address" @click="addressSign = 2" v-if="addressSign == 1 && otherAds.length">更多地址</div>
        <div class="hide-address" v-if="addressSign == 2">
          <span class="hide_1" @click="addressSign = 1">收起地址</span>
          <div class="address-list" v-for="item in otherAds" :key="item.id">
            <div class="content">
              <div class="content-left">
                <div class="address-first">
                  <p class="hide_2" @click="selectAddress(item)">
                    <span>{{item.name}}</span>
                    <span>{{item.provinceName}}</span>
                  </p>
                </div>
                <span class="name">{{item.name}}</span>
                <span>{{item.areaName}} {{item.address}} </span>
                <span class="phone">{{item.mobile}}</span>
              </div>
              <div class="content-right">
                <span class="default" v-if="item.status === 1">默认地址</span>
                <span class="set" @click="setDefault(item.id)" v-if="item.status === 0">设为默认地址</span>
                <span class="edit" @click="editAddress(item.id)">编辑</span>
                <span class="edit" @click="delAddress(item.id, item.status)">删除</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="user-content"  v-else style="padding:20px;text-align:center">暂无地址，请添加地址</div>
    </div>
    <!-- 订单货品 -->
    <div class="order-goods">
      <div class="hd">
        <p class="header">货单信息</p>
        <div class="w">
          <span class="good">商品</span>
          <span class="price">单价（元）</span>
          <span class="amount">数量</span>
          <span class="selloff">优惠（元）</span>
          <span class="sum">金额（元）</span>
        </div>
      </div>
      <div class="bd">
        <div class="store-box" v-for="(store, si) in order.shops" :key="si">
          <div class="store-name">供应商：{{store.storeName}}</div>
          <div class="good-box clearfix" v-for="(good, gi) in store.products" :key="gi">
            <div class="goods-img">
              <img :src="good.productCover" width="100%" height="100%">
            </div>
            <div class="goods-name">{{good.name}}</div>
            <div class="goods-info" v-for="(attr, ai) in good.attributes" :key="ai">
              <div class="good">
                <div class="goods-spec">规格:{{attr.attributeName}}</div>
              </div>
              <div class="good-price price">
                ¥{{attr.sellPrice}}
                <span class="original-price" v-if="attr.originalPrice">¥{{attr.originalPrice}}</span>
              </div>
              <div class="good-amount amount">x {{attr.amount}}</div>
              <div class="good-selloff selloff" :class="{'active': !good.isGift}">
                <span v-if="attr.orderProductReduceMoney">优惠：{{attr.orderProductReduceMoney}}</span>
                <span v-else>—</span>
                <el-tooltip class="desc" effect="light"  placement="right" v-if="attr.activityNames && attr.activityNames.length">
                  <div slot="content">{{attr.activityNames.toString()}}</div>
                  <i class="el-icon-question el-icon--right"></i>
                </el-tooltip>
              </div>
              <div class="good-sum sum">¥{{attr.prices}}</div>
            </div>
          </div>
          <div class="store-foot clearfix">
            <div class="remark">
              备注：<input class="input-remark" type="text" v-model="store.buyerRemark" placeholder="告诉卖家您的额外需求"/>
            </div>
            <div class="store-total">
              <p>运费：0.00</p>
              <p>店铺合计：¥{{store.shopPrice}}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 选择优惠券 -->
    <div class="coupon-wrapper">
      <div class="coupon-box">
        <span class="icon-coupon">惠</span>优惠券:
        <el-select size="medium" v-model="order.selectCouponId" placeholder="请选择优惠券" @change="balanceOrder">
          <el-option label="不使用优惠券" :value="0"></el-option>
          <el-option v-for="(item, index) in order.keSelectCoupons" :key="index" :label="item.pcCouponName" :value="item.couponId"></el-option>
        </el-select>
      </div>
      <span class="discount">优惠券：-{{order.couponDiscountsPrice}}</span>
    </div>
    <!-- 订单总览 -->
    <div class="order-census">
      <p class="tips">发票说明：该订单金额不含税，含税发票可在我的开票中心申请。</p>
      <p>货品总金额：¥{{order.totalPrice}}元</p>
      <p v-show="order.couponDiscountsPrice">优惠券：- {{order.couponDiscountsPrice}}元</p>
      <p v-show="order.discountsPrice">活动优惠：- {{order.discountsPrice}}元</p>
      <p>运费总计: 0</p>
      <p>应付金额： <span class="price">¥{{order.payPrice}}元</span></p>
    </div>
    <!-- 提交订单 -->
    <div class="order-bottom">
      <router-link to="/order/shopcart" class="btn-cart"><i class="el-icon-d-arrow-left"></i>返回采购单</router-link>
      <div class="btn-commit" @click="submitOrder">提交订单</div>
    </div>
    <!-- 新增/编辑收货地址 -->
    <el-dialog title="新增/编辑收货地址" :visible.sync="addressDialog" width="540px" :before-close="beforeClose">
      <el-form :model="addressForm" ref="addressForm" :rules="addressRules" label-width="100px">
        <el-form-item label="所在地区" prop="area">
          <el-cascader class="db" :options="areaData" v-model="addressForm.area" placeholder="请选择省市区"></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addressForm.address" placeholder="请填写详细地址，不得少于5个字"></el-input>
        </el-form-item>
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.name" placeholder="请填写收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addressForm.mobile" maxlength="11" placeholder="请填写收货人手机号码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="saveAddress">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AREA from '@/data/area'
import { getAreaName } from '@/util/getAreaName'
export default {
  data () {
    return {
      submitType: this.$route.query.submitType,
      addressSign: 1, // 1为展开所有地址 2为收起地址
      addressrList: [], // 所有地址
      defaultAds: {}, // 默认地址
      otherAds: [], // 默认地址除外的其他地址
      addressDialog: false,
      areaData: AREA, // 地区数据
      addressForm: {
        id: '', // 编辑时传入地址id
        area: [],
        address: '',
        name: '',
        mobile: ''
      },
      addressRules: {
        area: [
          {required: true, message: '请选择所在地区', trigger: 'change'}
        ],
        address: [
          {required: true, message: '详细地址不能为空', trigger: 'blur'},
          {validator: (rule, value, callback) => {
            if (!value) {
              return callback(new Error('详细地址不能为空'))
            }
            setTimeout(() => {
              if (value.length < 5) {
                return callback(new Error('地址最少包含5个字'))
              } else {
                callback()
              }
            }, 1000)
          },
          trigger: 'blur'}
        ],
        name: [
          {required: true, message: '收货人姓名不能为空', trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '收货人手机号码不能为空', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value.trim() === '') {
                callback(new Error('请输入手机号码'))
              } else if (!(/^1[3456789]\d{9}$/.test(value))) {
                callback(new Error('您输入手机号码不正确'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      orderId: '',
      order: {}
    }
  },
  beforeMount () {
    this.init()
  },
  methods: {
    // 初始化
    init () {
      // 获取核算订单信息
      this.order = JSON.parse(window.localStorage.getItem('orderInfo'))
      this.orderId = this.order.porderId
      this.order.shops.forEach(shop => {
        this.$set(shop, 'buyerRemark', '')
      })
      this.getAddress()
    },
    // 重新核算订单
    balanceOrder (val) {
      this.$http.post(this.$api + '/pc/order/balanceOrder', {
        porderId: this.order.porderId,
        couponId: this.order.selectCouponId || ''
      }).then(res => {
        if (res.responseCode === '0000') {
          window.localStorage.setItem('orderInfo', JSON.stringify(res.data))
          this.init()
        }
      })
    },
    // 获取收货地址
    getAddress () {
      this.$http.post(this.$api + '/pc/orderShipping/findAllByCustId', {
        page: 1,
        pageSize: 10000
      }).then(res => {
        if (res.responseCode === '0000') {
          this.addressrList = res.data
          this.addressrList.forEach(item => {
            item.provinceName = getAreaName([item.province])
            item.areaName = getAreaName([item.province, item.city, item.district])
            // 获取其他地址
            this.otherAds = []
            if (item.status !== 1) {
              this.otherAds.push(item)
            }
          })
          this.defaultAds = this.addressrList[0]
        }
      })
    },
    // 新增收货地址
    addAddress () {
      this.addressDialog = true
      this.$nextTick(() => {
        this.addressForm.area = []
        this.addressForm.name = ''
        this.addressForm.address = ''
        this.addressForm.mobile = ''
        this.addressForm.status = ''
        this.$refs.addressForm.resetFields()
      })
    },
    // 编辑收货地址
    editAddress (id) {
      this.addressForm.id = id
      this.$http.post(this.$api + '/pc/orderShipping/findById', {
        id: id
      }).then(res => {
        if (res.responseCode === '0000') {
          this.addressForm.area.push(res.data.province)
          this.addressForm.area.push(res.data.city)
          this.addressForm.area.push(res.data.district)
          this.addressForm.name = res.data.name
          this.addressForm.address = res.data.address
          this.addressForm.mobile = res.data.mobile
          this.addressForm.status = res.data.status
          this.addressDialog = true
        } else {
          this.$message.error({
            duration: this.$store.state.duration,
            message: res.responseMsg
          })
        }
      })
    },
    // 删除收货地址
    delAddress (id, status) {
      this.$http.post(this.$api + '/pc/orderShipping/deleteById', {
        id: id,
        status: status
      }).then(res => {
        if (res.responseCode === '0000') {
          this.$message.success({
            message: res.responseMsg,
            duration: this.$store.state.duration,
            onClose: () => {
              this.getAddress()
            }
          })
        }
      }).catch(() => {
        this.$message.error({
          message: '请求超时！'
        })
      })
    },
    // 是否不保存关闭
    beforeClose (done) {
      this.$confirm('确认不保存关闭？').then(_ => {
        done()
      }).catch(_ => {})
    },
    // 保存收货地址
    saveAddress () {
      this.$refs.addressForm.validate(valid => {
        if (valid) {
          // 判断操作类型
          if (this.addressForm.id) { // 编辑
            this.$http.post(this.$api + '/pc/orderShipping/updateById', {
              id: this.addressForm.id || '',
              name: this.addressForm.name,
              mobile: this.addressForm.mobile,
              address: this.addressForm.address,
              province: this.addressForm.area[0],
              city: this.addressForm.area[1] || '',
              district: this.addressForm.area[2] || '',
              status: this.addressForm.status
            }).then(res => {
              if (res.responseCode === '0000') {
                this.$message({
                  type: 'success',
                  duration: this.$store.state.duration,
                  message: res.responseMsg,
                  onClose: () => {
                    this.addressDialog = false
                    this.getAddress()
                  }
                })
                this.getAddress()
              } else {
                this.$message.error({
                  duration: this.$store.state.duration,
                  message: res.responseMsg
                })
              }
            })
          } else { // 新增
            this.$http.post(this.$api + '/pc/orderShipping/addShipping', {
              name: this.addressForm.name,
              province: this.addressForm.area[0],
              city: this.addressForm.area[1],
              district: this.addressForm.area[2],
              address: this.addressForm.address,
              mobile: this.addressForm.mobile
            }).then(res => {
              if (res.responseCode === '0000') {
                this.$message({
                  type: 'success',
                  duration: this.$store.state.duration,
                  message: res.responseMsg,
                  onClose: () => {
                    this.addressDialog = false
                    this.getAddress()
                  }
                })
                this.getAddress()
              } else {
                this.$message.error({
                  duration: this.$store.state.duration,
                  message: res.responseMsg
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 设为默认地址
    setDefault (id, status) {
      this.$http.post(this.$api + '/pc/orderShipping/updateById', {
        id: id,
        status: 1
      }).then(res => {
        if (res.responseCode === '0000') {
          this.addressSign = 1
          this.$message.success({
            message: res.responseMsg,
            duration: this.$store.state.duration,
            onClose: () => {
              this.getAddress()
            }
          })
        }
      }).catch(() => {
        this.$message.error({
          message: '请求超时！'
        })
      })
    },
    // 选择收货地址
    selectAddress (obj) {
      let currentAds = this.defaultAds
      this.defaultAds = obj
      for (let i = 0; i < this.otherAds.length; i++) {
        let item = this.otherAds[i]
        if (item.id === obj.id) {
          this.otherAds[i] = currentAds
        }
      }
      this.addressSign = 1
    },
    // 提交订单
    submitOrder () {
      // 设置getID
      let getId = ''
      this.order.keSelectCoupons.forEach(item => {
        if (item.couponId === this.order.selectCouponId) {
          getId = item.getId
        }
      })
      let param = {
        address: {}, // 收货信息
        submitType: this.submitType, // 提交类型： 0-立即购买，1-购物车结算
        isOldTea: this.$route.query.isOldTea, // 是否为老茶 1:是； 2否
        shops: [], // 店铺-商品集合
        porderId: this.order.porderId || '', // 订单id
        couponId: this.order.selectCouponId || '', // 优惠券id
        getId: getId || '',
        cartAttributeIds: '' // 购物车属性id集合
      }
      // 加入收货信息
      let receiver = {
        name: this.defaultAds.name,
        mobile: this.defaultAds.mobile,
        province: this.defaultAds.province,
        city: this.defaultAds.city,
        district: this.defaultAds.district,
        address: this.defaultAds.address
      }
      param.address = JSON.stringify(receiver)
      // 加入店铺-商品集合
      let arr = []
      this.order.shops.forEach(item => {
        arr.push({
          orderId: item.orderId,
          buyerRemark: item.buyerRemark || ''
        })
      })
      param.shops = JSON.stringify(arr)
      // 加入购物车属性id集合
      if (Number(this.submitType) === 1) {
        this.order.shops.forEach(shop => {
          shop.products.forEach(good => {
            good.attributes.forEach(attr => {
              if (attr.cartAttributeId) {
                param.cartAttributeIds += attr.cartAttributeId + ','
              }
            })
          })
        })
      }
      this.$http.post(this.$api + '/pc/order/submitOrder', param).then(res => {
        if (res.responseCode === '0000') {
          this.$message.success({
            duration: this.$store.state.duration,
            message: res.responseMsg,
            onClose: () => {
              if (Number(this.$route.query.isOldTea) === 1) { // 如果是老茶订单则跳转订单页待客服确认
                this.$router.push('/user/order')
              } else {
                this.$router.push({
                  path: '/order/payment',
                  query: {
                    orderId: this.orderId
                  }
                })
              }
            }
          })
        } else {
          this.$message.error({
            duration: this.$store.state.duration,
            message: res.responseMsg
          })
        }
      }).catch(err => {
        console.error(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/scss/basic.scss';
.order-page {
  margin: auto;
  width: 1200px;
  .header {
    margin-bottom: 20px;
    font-size: 20px;
    color: $f_main;
  }
}
.address-wrapper{
  position: relative;
  margin-top: 20px;
  padding: 15px 20px;
  background: #ffffff;
  border: solid 1px $border_color;
  border-bottom: 0;
  .btn-add {
    position: absolute;
    top: 20px;
    right: 45px;
  }
  .address-content {
    position: relative;
    .content{
      display: flex;
      justify-content: space-between;
      font-size: $fz_14;
      padding-top: 20px;
      .content-left{
        .address-first{
          // width: 140px;
          margin-right: 25px;
          padding-bottom: 7px;
          display: inline-block;
          p{
            // width: 142px;
            box-sizing: border-box;
            padding: 6px 20px 6px 0;
            span{
              padding-left: 16px;
            }
          }
          p.address-default{
            border: 2px solid $border_red;
            background: url(../../assets/images/icon-select.png) no-repeat right bottom;
          }
        }
        .name{
          margin-right: 30px;
        }
        .phone{
          margin-left: 40px;
        }
      }
      .content-right{
        margin-right: 25px;
        .set{
          color: $f_normal;
          border-bottom: 1px solid $f_normal;
          cursor: pointer;
        }
        .default{
          color: #ffffff;
          background: $success;
          margin-left: 15px;
          padding: 3px 6px;
          border-radius: 3px;
        }
        .edit{
          margin-left: 12px;
          color: $font-blue;
          border-bottom: 1px solid $font-blue;
          cursor: pointer;
          line-height: 32px;
        }
      }
    }
    & form {
      padding: 35px 0 25px 0;
      .el-input{
        width: 500px;
      }
    }
    .more-address{
      width: 70px;
      font-size: $fz_14;
      color: $font-blue;
      padding:10px 0 20px 0;
      background: url(../../assets/images/icon-down.png) no-repeat  60px 15px;
      cursor: pointer;
    }
    .hide-address{
      width: 100%;
      font-size: $fz_14;
      padding:5px 0 20px 0;
      background:#ffffff url(../../assets/images/icon-up.png) no-repeat  85px 10px;
      border: 1px solid $border_color;
      box-shadow: 0px 3px 6px rgba(128, 128, 128, 0.3);
      position: absolute;
      z-index: 2;
      .hide_1{
        cursor: pointer;
        padding-left: 25px;
        color: $f_normal;
      }
      .content{
        margin:0 25px;
        border-bottom: 1px dotted $border-color;
        .content-right{
          margin-right: 0;
        }
        .set{
          color: $f_normal;
          border-bottom: 1px solid $f_normal;
          cursor: pointer;
        }
      }
      .hide_2{
        border: 2px solid $border-color;
        cursor: pointer;
        &:hover {
          border: 2px solid $border_red;
          background: url(../../assets/images/icon-select.png) no-repeat right bottom;
        }
      }
    }
  }
}
.order-goods {
  .hd {
    padding: 0 20px;
    background: #ffffff;
    border-left: 1px solid $border_color;
    border-right: 1px solid $border_color;
    .w {
      display: flex;
      align-items: center;
      height: 30px;
      background: $bg_color;
      text-align: center;
      font-size: $fz_14;
    }
  }
  .bd {
    .store-box {
      padding: 0 20px;
      background: #ffffff;
      border: solid 1px $border_color;
      &:first-child {
        border-top: 0;
      }
      .store-name {
        padding: 15px 0 20px;
        font-size: 14px;
        color: $f_normal;
      }
      .good-box {
        margin-bottom: 20px;
        padding: 25px 0 25px 25px;
        background: #f7f9ff;
        border: solid 1px $border_color;
        .goods-img {
          float: left;
          margin-right: 25px;
          width: 140px;
          height: 140px;
          border: solid 1px $border_color;
        }
        .goods-name {
          margin-top: 8px;
          float: left;
          width: 350px;
          height: 40px;
          font-size: $fz_16;
          line-height: 1.25;
          color: $f_main;
          overflow:hidden;
          text-overflow:ellipsis;
          display:-webkit-box;
          -webkit-box-orient:vertical;
          -webkit-line-clamp:2;
        }
        .goods-info {
          float: left;
          display: flex;
          width: 966px;
          height: 30px;
          align-items: center;
          text-align: center;
          color: $f_main;
          .goods-spec {
            text-align: left;
          }
          .original-price {
            padding-left: 4px;
            color: $f_sub;
          }
          .good-selloff {
            opacity: 0;
            font-size: $fz_14;
            &.active {
              opacity: 1;
            }
          }
          .good-sum {
            color: $red;
          }
        }
      }
      .store-foot {
        margin: 20px 0;
        font-size: $fz_14;
        .remark {
          float: left;
          .input-remark {
            margin-left: 10px;
            padding-left: 10px;
            width: 400px;
            height: 28px;
            border: solid 1px $border_color;
            &:disabled {
              background: $bg_color;
              cursor: no-drop;
            }
          }
        }
        .store-total {
          float: right;
          text-align: right;
          font-size: 14px;
          line-height: 28px;
          color: $f_normal;
        }
      }
    }
  }
  .good {
    flex: 1;
  }
  .price {
    width: 160px;
  }
  .amount {
    width: 140px;
  }
  .selloff {
    width: 150px;
  }
  .sum {
    width: 150px;
  }
}
.coupon-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 65px;
  font-size: 14px;
  color: $f_normal;
  background: #ffffff;
  border: solid 1px $border_color;
  border-top: 0;
  .icon-coupon {
    display: inline-block;
    vertical-align: top;
    margin-top: 9px;
    margin-right: 5px;
    width: 16px;
    height: 16px;
    line-height: 16px;
    text-align: center;
    font-size: 12px;
    color: #ffffff;
    background: $red;
    border-radius: 2px;
  }
}
.order-census {
  position: relative;
  margin: 25px 0;
  padding: 10px 25px;
  text-align: right;
  font-size: 14px;
  color: $f_normal;
  background: #ffffff;
  border: solid 1px $border_color;
  .tips {
    position: absolute;
    top: 25px;
    left: 25px;
    margin: 0;
  }
  p {
    margin: 15px 0;
  }
  .price {
    font-size: $fz_20;
    color: $red;
  }
}
.order-bottom {
  margin: 40px 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .btn-cart {
    color: $f_normal;
    cursor: pointer;
    .el-icon-d-arrow-left {
      margin-right: 6px;
    }
    &:hover {
      text-decoration: underline;
    }
  }
  .btn-commit {
    margin-left: 35px;
    width: 120px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: #ffffff;
    background: $red;
    border-radius: 4px;
    cursor: pointer;
    &:hover {
      background: $red_l;
    }
    &:active {
      background: $red_d;
    }
  }
}
</style>
